package com.android.fragmentdemo.defineviews;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;
import androidx.annotation.NonNull;

public class CenterImageSpan extends ImageSpan {
    private final int leftDistance;
    private final int rightDistance;

    public CenterImageSpan(Drawable drawableRes,int leftDistance,int rightDistance) {
        super(drawableRes);
        this.leftDistance = leftDistance;
        this.rightDistance = rightDistance;
    }

    public CenterImageSpan(Context context,int drawableRes,int leftDistance,int rightDistance) {
        super(context, drawableRes);
        this.leftDistance = leftDistance;
        this.rightDistance = rightDistance;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        Drawable d = getDrawable();
        Rect rect = d.getBounds();
        if (fm != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.bottom - fmPaint.top;
            int drHeight = rect.bottom - rect.top;

            int top = (int) (drHeight / 2F - fontHeight / 4F + 0.5F);
            int bottom = (int) (drHeight / 2F + fontHeight / 4F + 0.5F);

            fm.ascent = -bottom;
            fm.top = -bottom;
            fm.bottom = top;
            fm.descent = top;
        }
        return rect.right + leftDistance + rightDistance;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, @NonNull Paint paint) {
        Drawable b = getDrawable();
        canvas.save();
        int transY = (int) (((bottom - top) - b.getBounds().bottom) / 2F + top + 0.5F);
        canvas.translate(x + leftDistance, transY);
        b.draw(canvas);
        canvas.restore();
    }
}
